package com.bajiao.service.product.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bajiao.common.constant._Whole;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.common.util.FastJsonHelper;
import com.bajiao.entity.cart.Cart;
import com.bajiao.entity.product.Product;
import com.bajiao.entity.store.Store;
import com.bajiao.mapper.product.ProductMapper;
import com.bajiao.service.cart.CartService;
import com.bajiao.service.product.ProductService;
import com.bajiao.service.visitor.VisitorService;
import com.bajiao.vo.product.ProductDetailsResponse;
import com.bajiao.vo.product.ProductResponse;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 产品表
 * @Author: FanJq
 * @Date:   2024-12-13
 * @Version: V1.0
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private VisitorService visitorService;

    /**
     * @Description
     * 获取店铺商品
     * @date 2024/12/14 9:24
     * @author FanJq
     * @param storeId
     * @return {@link List< ProductResponse>}
    */
    @Override
    public List<ProductResponse> getProductList(String userId, String storeId, String classifyId) {
//        List<Product> productList = super.lambdaQuery()
//                .eq(Product::getStoreId, storeId)
//                .eq(Product::getClassifyId, classifyId)
//                .eq(Product::getStatus, _Whole.ONE)
//                .eq(Product::getDelFlag, _Whole.ZERO)
//                .orderByDesc(Product::getCreateTime)
//                .list();
//        List<ProductResponse> responseList = productList.stream().map(product -> {
//            ProductResponse response = FastJsonHelper.beanToBean(product, ProductResponse.class);
//            return response;
//        }).collect(Collectors.toList());
        List<ProductResponse> responseList = super.baseMapper.getProductList(userId, storeId, classifyId);
        return responseList;
    }

    /**
     * @Description
     * 商品详情
     * @date 2024/12/14 9:24
     * @author FanJq
     * @param storeId
     * @param productId
     * @return {@link ProductDetailsResponse}
    */
    @Override
    public ProductDetailsResponse getProductDetails(String userId, String storeId, String productId) {
        Product product = this.getById(storeId, productId);
        if (ObjectUtil.isNull(product))
            throw new DataHandleException("产品已下架");
        ProductDetailsResponse response = FastJsonHelper.beanToBean(product, ProductDetailsResponse.class);
        response.setSliderImageList(Arrays.asList(response.getSliderImage().split(StringPool.COMMA)));
        Cart cart = super.baseMapper.getProductCartInfo(userId, productId);
        if (ObjectUtil.isNotNull(cart)) {
            response.setBuyNum(cart.getBuyNum());
            response.setCartId(cart.getId());
        }
        //@create by FanJq 2024/12/16 17:54 处理浏览量
        this.addBrowse(productId);
        return response;
    }

    /**
     * @Description
     * 获取推荐商品
     * @date 2025/1/13 14:06
     * @author FanJq
     * @param storeId
     * @param productIds
     * @return {@link List< ProductResponse>}
    */
    @Override
    public List<ProductResponse> getProductRecommend(String userId, String storeId, String productIds) {
//        List<String> idList = new ArrayList<>();
//        if (StrUtil.isNotBlank(productIds)) {
//            idList = Arrays.asList(productIds.split(StringPool.COMMA));
//        }
//        List<Product> productList = super.lambdaQuery()
//                .eq(Product::getStoreId, storeId)
//                .notIn(CollectionUtil.isNotEmpty(idList), Product::getId, idList)
//                .eq(Product::getStatus, _Whole.ONE)
//                .eq(Product::getDelFlag, _Whole.ZERO)
//                .last("ORDER BY RAND()")
//                .list();
//        List<ProductResponse> responseList = productList.stream().map(product -> {
//            ProductResponse response = FastJsonHelper.beanToBean(product, ProductResponse.class);
//            return response;
//        }).collect(Collectors.toList());
        List<ProductResponse> responseList = super.baseMapper.getProductRecommend(userId, storeId, productIds);
        return responseList;
    }

    /**
     * @Description
     * 根据商品id获取
     * @date 2024/12/14 9:26
     * @author FanJq
     * @param storeId
     * @param productId
     * @return {@link Product}
    */
    @Override
    public Product getById(String storeId, String productId) {
        Product product = super.lambdaQuery()
                .eq(Product::getId, productId)
                .eq(Product::getStoreId, storeId)
                .eq(Product::getStatus, _Whole.ONE)
                .one();
        return product;
    }

    /**
     * @Description
     * 处理浏览记录
     * @date 2024/12/16 17:54
     * @author FanJq
     * @param productId
     * @return
    */
    private void addBrowse(String productId) {
        //@create by FanJq 2024/12/13 10:21 递增浏览量
        super.lambdaUpdate().setSql("browse = browse + 1").eq(Product::getId, productId).update();
        //visitorService.record();
    }

    /**
     * @Description
     * 处理销量
     * @date 2024/12/16 17:54
     * @author FanJq
     * @param productId
     * @return
    */
    @Override
    @Async("taskExecutor")
    public void salesLogic(String productId, Integer flag, Integer buyNum) {
        LambdaUpdateChainWrapper<Product> updateSql = super.lambdaUpdate()
                .eq(Product::getId, productId);
        if (flag.intValue() == _Whole.ONE) {
            updateSql.setSql("sales = sales + " + buyNum);
        } else if (flag.intValue() == _Whole.TWO) {
            updateSql.setSql("sales = sales - " + buyNum);
        }
        updateSql.update();
    }
}
